'use strict';

import Base from './base.js';
import pagination from 'think-pagination';//引入分页插件
var fs = require('fs');
var path = require('path');
export default class extends Base {

  init(http) {
    super.init(http);
  }

  //后台主界面
  async indexAction() {
    //分页
    let where = 'is_publish = 1 and pid = 0';
    if (this.get('key')) {
      let k = this.get('key');
      where += " and title like '%" + k + "%' ";
      this.assign('key', k);
    }
    let dataList = await this.model('category').dataList(where);
    //this.end(dataList);
    this.assign('dataList', dataList);
    return this.display('admin/category/index');
  }

  //详情
  async detailAction() {
    if (this.get('id')) {
      let where = 'id = ' + this.get('id');
      let obj = await this.model('category').where(where).find();
      //this.end(data);
      if (think.isEmpty(obj)) {
        error('该信息可能已被删除', this.http);
      }
      this.assign('obj', obj);
    }


    let where = 'is_publish = 1 and pid = 0';
    let cat = await this.model('category').dataList(where);
    this.assign('cat', cat);
    
    return this.display('admin/category/detail')
  }

  //处理事件
  async dosthAction(){
    let post = this.post();
    
    //这里的 key 需要和 form 表单里的 name 值保持一致
    var file = think.extend({}, this.file('imgFile'));
    
    //过大不允许上传
    if(file.size > this.config('max_upload')){
       error('上传失败，图片过大', this.http);
    }

     //获取判断是否图片
    if(!isImg(file.originalFilename)){
       error('只能上传'+this.config('img_type')+'的图片', this.http);
    }

    
    var filepath = file.path;

    //文件上传后，需要将文件移动到项目其他地方，否则会在请求结束时删除掉该文件
    var basePath =  this.config('publich_path')+'upload/editor/'+dateformat('yyyymmdd',new Date())+'/';
    var uploadPath = think.RESOURCE_PATH +basePath;
    think.mkdir(uploadPath);
    var basename = path.basename(filepath);
    fs.renameSync(filepath, uploadPath + '/' + basename);
    file.path = uploadPath + '/' + basename;
    if (think.isFile(file.path)) {
      var url = basePath+basename;
    } else {
       error('上传失败，可能图片过大或格式问题', this.http);
    }
    

    post.image = url;
    let obj = await this.model('category').add(post);

    return this.success(obj);
  }

}